//
//  SMUtil.m
//  StoneMason
//
//  Created by iOS1 on 16/12/5.
//  Copyright © 2016年 iOS1. All rights reserved.
//

#import "SMUtil.h"
#import "HYBPhotoPickerManager.h"
#import "SysInfo.h"
#import "Login_VC.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <AVFoundation/AVFoundation.h>
#import <Photos/Photos.h>
#import "DataEncrptDES.h"
#import "Home_VC.h"


#define AFWEBAPI_REQUEST_TIMEOUT 20

@interface SMUtil()<UIAlertViewDelegate>

@end

@implementation SMUtil

+(void)requestWithMethod:(NetWorkFunction)function with:(NSString *)urlStr parameters:(NSMutableDictionary *)parameters  success:(sucBlock)success faild:(faild)faild {
    if (![self isConnectionAvailable]) { //检测网络
        NSString *title = @"网络不通，请检测网络";
        [ToolHelper showRequestStatus:title type:0];
        return;
    }
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    manager.securityPolicy = [self customSecurityPolicy];
    urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", nil];
    manager.requestSerializer.timeoutInterval = AFWEBAPI_REQUEST_TIMEOUT;
    NSString *token = @"";
    if (isLogin()) {
        token = [UserData instance].getUserInfo.token;
    }
    
    NSString *version = @"v.1.0"; //[NSString stringWithFormat:@"v.%@",SysInfo.getVersion];
    NSString *uuid = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    
    //语言包
    NSString *language = [[NSUserDefaults standardUserDefaults] objectForKey:@"myLanguage"];
    
    if (language.length == 0) {
        language = @"zh-Hans";
    }
    if ([language isEqualToString:@"en"]) {
        language = @"en-us";
    }
    NSString *random = [ToolHelper getRandomStringWithNum:32];
    [parameters setObject:version forKey:@"apiversion"];
    [parameters setObject:uuid forKey:@"uuid"];
    [parameters setObject:random forKey:@"nonce"];
    [parameters setObject:language forKey:@"l"];
    
    NSString *securityJsonStr = [DataEncrptDES signStr:parameters];
    [parameters setObject:securityJsonStr forKey:@"sign"];
    
    if (token.length > 1) {
        [parameters setObject:token forKey:@"token"];
    }
    
    switch (function) {
        case NetWorkFunctionPost:
        {
            [manager POST:urlStr parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                NSDictionary *resultDict = responseObject[@"data"];
                int code = [resultDict[@"error"]intValue];
                NSString *msg = resultDict[@"error_msg"];
                
                if (code == HTTPNOERRO) {
                    return success(resultDict);
                }else if (code == 100004) {
                    BaseViewController *rootVc = (BaseViewController *)[UIApplication sharedApplication].keyWindow.rootViewController;
                    BaseViewController *curVC = (BaseViewController *)rootVc.childViewControllers.lastObject;
                    [[UserData instance] setLoginState:NO];
                    Login_VC *loginVc = [[Login_VC alloc] init];
                    [curVC presentViewController:loginVc animated:YES completion:nil];
                }else return faild(msg,code);
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                //设置登录失效
                NSDictionary *dic = error.userInfo;
                NSString *stuatueCode = dic[@"NSLocalizedDescription"];
                if ([stuatueCode containsString:@"401"]) {
                    return ;
                }
//                NSLog(@"%@", error.description);
                return faild(@"啊哦,貌似网络出了点问题",HAVEERRO);
            }];
        }
            break;
        case NetWorkFunctionGet:
        {
            [manager GET:urlStr parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                NSDictionary *resultDict = responseObject[@"data"];
                int code = [responseObject[@"error"]intValue];
                NSString *msg = responseObject[@"message"];
                
                if (code == HTTPNOERRO) {
                    return success(resultDict);
                }
                else return faild(msg,code);
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                //设置登录失效
                NSDictionary *dic = error.userInfo;
                NSString *stuatueCode = dic[@"NSLocalizedDescription"];
                if ([stuatueCode containsString:@"401"]) {
                    return ;
                }
                NSLog(@"%@", error.description);
                return faild(@"啊哦,貌似网络出了点问题",HAVEERRO);
            }];
        }
            break;
        default:
            break;
    }
}

+(void)uploadImgWithUrl:(NSString *)URLString uploadImg:(NSArray *)images
             imgType:(NSString *)imgType parameters:(id)parameters success:(void (^)(NSURLSessionDataTask *, id))success failure:(void (^)(NSURLSessionDataTask *, NSError *))failure {
    
    if (![self isConnectionAvailable]) { //检测网络
        NSString *title = @"网络不通，请检测网络";
        [ToolHelper showRequestStatus:title type:0];
        return;
    }
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    manager.securityPolicy = [self customSecurityPolicy];
//    [manager.requestSerializer setValue:[UserData instance].getUserInfo.token forHTTPHeaderField:@"TOKEN"];
    
    NSString *token = @"";
    if (isLogin()) {
        token = [UserData instance].getUserInfo.token;
    }
    
    if (token.length > 1) {
        [manager.requestSerializer setValue:token forHTTPHeaderField:@"TOKEN"];
    }
    NSString *version = @"v.1.0"; //[NSString stringWithFormat:@"v.%@",SysInfo.getVersion];
    NSString *uuid = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    NSString *random = [ToolHelper getRandomStringWithNum:32];
    [parameters setObject:version forKey:@"apiversion"];
    [parameters setObject:uuid forKey:@"uuid"];
    [parameters setObject:random forKey:@"nonce"];
    
    NSString *securityJsonStr = [DataEncrptDES signStr:parameters];
    [parameters setObject:securityJsonStr forKey:@"sign"];
    
    [parameters setObject:images[0] forKey:imgType];

    __block NSInteger count = images.count - 1;
    manager.requestSerializer.timeoutInterval = AFWEBAPI_REQUEST_TIMEOUT;
    NSString *timeStemp = [NSDate currentSystemMillisecond];
    [manager POST:URLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData > _Nonnull formData) {
        for (int i = 0; i < images.count; i++) {
            NSString *fileName  = [NSString stringWithFormat:@"%@_%ld.png",timeStemp, (long)count];
            NSData *imageData = [HYBPhotoPickerManager imgdataForUpload:images[count]];
            [formData appendPartWithFileData:imageData name:imgType fileName:fileName mimeType:@"image/png"];
            count--;
        }
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        return success(task,responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        return failure(task,error);
    }];
}

+ (AFSecurityPolicy*)customSecurityPolicy {
    NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"stonemasons" ofType:@"cer"];
    NSData *cerData = [NSData dataWithContentsOfFile:cerPath];
    
    //使用证书验证模式
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
    
    // allowInvalidCertificates 是否允许无效证书（也就是自建的证书），默认为NO
    // 如果是需要验证自建证书，需要设置为YES
    securityPolicy.allowInvalidCertificates = YES;
    
    //validatesDomainName 是否需要验证域名，默认为YES；
    //假如证书的域名与你请求的域名不一致，需把该项设置为NO；如设成NO的话，即服务器使用其他可信任机构颁发的证书，也可以建立连接，这个非常危险，建议打开。
    //置为NO，主要用于这种情况：客户端请求的是子域名，而证书上的是另外一个域名。因为SSL证书上的域名是独立的，假如证书上注册的域名是www.google.com，那么mail.google.com是无法验证通过的；当然，有钱可以注册通配符的域名*.google.com，但这个还是比较贵的。
    //如置为NO，建议自己添加对应域名的校验逻辑。
    securityPolicy.validatesDomainName = NO;
    securityPolicy.pinnedCertificates = [NSSet setWithObject:cerData];
    return securityPolicy;
}

+ (BOOL)isConnectionAvailable
{
    SCNetworkReachabilityFlags flags;
    BOOL receivedFlags;
    
    SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(CFAllocatorGetDefault(), [@"baidu.com" UTF8String]);
    receivedFlags = SCNetworkReachabilityGetFlags(reachability, &flags);
    CFRelease(reachability);
    
    if (!receivedFlags || (flags == 0) )
    {
        return FALSE;
    } else {
        return TRUE;
    }
}

+(void)listenNetworkStateChangeBlock:(void(^)(NSInteger status))networkStatus {
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                //未识别的网络
                networkStatus(-1);
                break;
            case AFNetworkReachabilityStatusNotReachable:
                //未连接
                networkStatus(0);
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                //移动网络
                networkStatus(1);
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                //wifi
                networkStatus(2);
                break;
        }
    }];
    [manager startMonitoring];
}

+(void)showAlertWithStr:(NSString *)content {
    if (![UserData instance].isAlertViewShowed) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"" message:content delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [UserData instance].isAlertViewShowed = YES;
        alert.delegate = self;
        [alert show];
    }
}

+(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    //延迟执行
    double delayInSeconds = 3.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
//        [UserData instance].isAlertViewShowed = NO;;
    });
}

@end
